package com.weituotian.system.dao.impl;

import com.weituotian.system.dao.IRoleDao;
import com.weituotian.system.entity.Role;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Repository
public class RoleDao extends BaseDao<Role, Integer> implements IRoleDao {

    @Override
    protected String getEntityName() {
        return "Role";
    }

    @Override
    protected String getIdFieldName() {
        return "id";
    }

    /**
     * 从角色实体列表中提取出各个角色的名字,组成Set集合
     *
     * @param roles 角色list
     * @return
     */
    @Override
    public Set<String> getRoleNameSet(List<Role> roles) {
        Set<String> roleSet = new HashSet<>();
        for (Role role : roles) {
            String name = role.getName();
            if (StringUtils.isNotBlank(name)) {
                roleSet.add(name);
            }
        }
        return roleSet;
    }

    @Override
    public List<Role> findRolesByUserId(Integer userId) {
        //待定
//        String jpql = "select role from Role role left join role.users user where user.id=:userId";
        String jpql = "select role from User user left join user.roles role where user.id=:userId";
        Query query = getSession().createQuery(jpql, Role.class);
        query.setParameter("userId", userId);
        return query.getResultList();
    }

}
